<?php 
require "py_class.php";
/**
 * A plugin for Chinese users. Make the slug can be filled with Pinyin form of title and tag
 *
 * @todo It needs a ui configure function for people who want to tune it.
 */
class ChinesePlugin extends Plugin
{
	/**
	 *  Provide plugin info to the system
	 */
	function info()
	{
		return array(
			'name' => 'Chinese Plugin',
			'version' => '0.5',
			'url' => 'http://shihui.org/sheng/chinese-plugin-for-habari',
			'author' => 'Mike Shi',
			'authorurl' => 'http://shihui.org/',
			'license' => 'Apache License 2.0',
			'description' => 'The plugin is for better chinese support',
		);
	}

	/**
	 * Convert the string into Pinyin
	 * @param string $string The string that is going to be Pinyin
	 * @return string The string of the $string's Pinyin form
	 */
	private function get_pyslug($string)
	{
		$py = new py_class();
		$length = self::getvar('length');
		$length += 0;
		if ($length <1 or $length > 100 ) {
			$length = 100;
		}
		$ret = strtolower($py->str2py($string, $length));
		return $ret;
	}

	/**
	 * Get the tag_slug in Pinyin form of tag_text
	 * @param string $string The tag_text string that is going to be Pinyin
	 * @return string The string of the $string's Pinyin form
	 */
	private function get_tag_slug($string)
	{
		$slug = $this->get_pyslug($string);
		$postfix= '';
		$postfixcount= 0;
		do {
			if (! $slugcount = DB::get_row( 'SELECT COUNT(tag_slug) AS ct FROM '
				. DB::table('tags') .
				' WHERE tag_slug = ? AND tag_text <> ?;',
				array( $slug . $postfix, $string ) ))
			{

				Utils::debug( DB::get_errors() );
				exit;
			}
			if ( $slugcount->ct != 0 ) $postfix = "-" . ( ++$postfixcount );
		} while ( $slugcount->ct != 0 );
		return $slug . $postfix;

	}

	/**
	 * Check whether the function is called from save_tags function
	 * @return boolean TRUE if the function is called from save_tags, or FALSE
	 */
	private function is_call_from_save_tags()
	{
		$bt = debug_backtrace();
		foreach ($bt as $value)
		{
			
			if (isset($value['class']) && $value['class'] == 'Post'
				&& $value['function'] === 'save_tags')
			{
				return true;	
			}
		}
		return false;
	}

	/**
	 * Return the Pinyin form tag_slug if the function is called by 
	 * save_tags function
	 * @param string $slug The slug of post title or tag_text
	 * @param string $string The post title or tag_text
	 * @return string If the function is called from save_tags, return the Pinyin form slug of tag_text, or return the $slug
	 */
	function filter_slugify($slug, $string)
	{
		if ($this->is_call_from_save_tags())
		{
			return $this->get_tag_slug($string);	
		}
			
		return $slug;
	}

	/**
	 * Return the Pinyin form of post's slug
	 * @param string $value The original slug of the post, it is title usually
	 * @return string The Pinyin form of the $value
	 */
	function filter_post_setslug($value)
	{
		return $this->get_pyslug($value);
	}

	/**
	 * A plugin level patch for ticket #165
	 *
	 * @param Post $post The post instance that wants to be process
	 * @param string $value The old slug of the post
	 * @param string $newvalue The new slug of the post 
	 * @todo It should be removed as soon as this bug is fixed by official
	 */
	function action_post_update_slug($post, $value, $newvalue)
	{
		//NOTE: It's just a patch for #165, so it does NOT need if the bug
		//is fixed.
		
		//if the user's slug string is empty, use the old slug
		if (strlen($newvalue) == 0)
		{
			//if the old value is empty string too, use title's pinyin.
			if (strlen($value) == 0)
			{
				$post->slug = $this->get_pyslug($post->title);
			}
			else
			{
				$post->slug = $value;
			}
		}
	}

	/**
	 * Search the all posts with invalid slug and to fix their post slug
	 */
	private function regenerate_post_slug()
	{
		$posts = Posts::get(array('nolimit'=>true, 'orderby'=>'pubdate ASC'));
		foreach ($posts as $post)
		{
			if (empty($post->slug ) || preg_match( "/^(-+\d+)+/", $post->slug) )
			{
				$post->slug = $this->get_pyslug($post->title);
				$post->update();
			}
		}
	}

	/**
	 * Search the all tags with invalid slug and to fix them
	 */
	private function regenerate_tag_slug()
	{
		$tags= DB::get_results( 'SELECT * FROM ' . DB::table('tags') );
		if (! $tags)
		{
			Utils::debug( DB::get_errors() );
			exit;
		}
		foreach ($tags as $tag)
		{
			if ( empty( $tag->tag_slug ) || preg_match( "/^(-+\d+)+/", $tag->tag_slug ) )
			{
				$sql = 'UPDATE ' . DB::table( 'tags' ) .  ' SET tag_slug = \'' . 
					$this->get_tag_slug($tag->tag_text) . '\' WHERE id = ' . $tag->id;
				if (! DB::exec( $sql) ) 
				{
					Utils::debug( DB::get_errors() );
					exit;
				}
			}
		}
	}

	/**
	 * After the plugin is activated, to fix all posts and tags with 
	 * invalid slug
	 */
	function action_plugin_activation($file)
	{
		$this->regenerate_post_slug();
		$this->regenerate_tag_slug();
	}

        public function filter_plugin_config($actions, $plugin_id) {
                if ($plugin_id == $this->plugin_id()) {
                        $actions[] = _t('Configure');
                }
                return $actions;
        }

        public function action_plugin_ui($plugin_id, $action) {
                if ($plugin_id == $this->plugin_id()) {
                        switch ($action) {
                                case _t('Configure'):
                                        $ui = new FormUI(strtolower(get_class($this)));
                                        $chinese_len= $ui->add('text', 'length', _t('Max Title Length'));
                                        $ui->on_success(array($this, 'updated_config'));
                                        $ui->out();
                                break;
                        }
                }
        }

        public function updated_config($ui) {
                return true;
        }

        private static function getvar($var) {
                return Options::get('chineseplugin:'.$var);
        }

}
?>

